import axios from "axios";
import { getToken, removeToken } from "@/utils";
import router from "@/router";


const request = axios.create({
    baseURL: 'http://geek.itheima.net/v1_0',
    timeout: 5000
})

// axios请求拦截器
request.interceptors.request.use(config => {
    const token = getToken()
    if (token) {
        config.headers.Authorization = `Bearer ${token}`
    }
    return config
}, e => Promise.reject(e))

// axios响应式拦截器
request.interceptors.response.use(res => res.data, e => {
    // 401 token 失效处理
    if (e.response.status === 401) {
        removeToken()
        router.navigate('/login')
        // 刷新页面 redux仓库也清空了
        window.location.reload()
    }

    return Promise.reject(e)
})

export { request }